﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;

namespace Shared.Logging
{
    public static class LoggingServiceCollectionExtensions
    {
        /// <summary>
        /// 添加logging服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="minimumLevel"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        public static IServiceCollection AddLoggingService(this IServiceCollection services, LoggingSettings settings)
        {
            ArgumentNullException.ThrowIfNull(settings);

            if (string.IsNullOrWhiteSpace(settings.FilePath))
                throw new ArgumentException("FilePath is required.", nameof(settings.FilePath));
            
            var logger = new LoggerConfiguration()
                .MinimumLevel.Is(StrToLogEventLevel(settings.LogLevel))
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.File(
                    path: settings.FilePath,
                    rollingInterval: RollingInterval.Hour,
                    shared: true)
                .CreateLogger();

            services.AddLogging(builder =>
            {
                // 清除默认提供程序
                builder.ClearProviders();
                builder.AddSerilog(logger, dispose: true);
            });

            return services;
        }

        private static LogEventLevel StrToLogEventLevel(string? level)
        {
            return (level ?? string.Empty).ToLowerInvariant() switch
            {
                "verbose" => LogEventLevel.Verbose,
                "debug" => LogEventLevel.Debug,
                "information" => LogEventLevel.Information,
                "warning" => LogEventLevel.Warning,
                "error" => LogEventLevel.Error,
                "fatal" => LogEventLevel.Fatal,
                _ => LogEventLevel.Information
            };
        }
    }
}
